﻿using LD.Tool;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Windows;

namespace LD.Host
{
    internal class Cache
    {
        private static string filePath = Path.Combine(Appbus.BasePath, "Config\\cache.config");

        /// <summary>  
        /// 获取数据缓存  
        /// </summary>  
        /// <param name="cacheKey">键</param>  
        public static object GetCache(string cacheKey)
        {
            var objCache = HttpRuntime.Cache.Get(cacheKey);
            return objCache;
        }
        /// <summary>  
        /// 设置数据缓存  
        /// </summary>  
        public static void SetCache(string cacheKey, object objObject)
        {
            var objCache = HttpRuntime.Cache;
            var val = objCache.Get(cacheKey);
            if (val == null)
                objCache.Insert(cacheKey, objObject);
            else
                objCache[cacheKey] = objObject;
        }
        /// <summary>  
        /// 设置数据缓存  
        /// </summary>  
        public static void SetCache(string cacheKey, object objObject, int timeout = 7200)
        {
            try
            {
                if (objObject == null) return;
                var objCache = HttpRuntime.Cache;
                //相对过期  
                //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue,  new TimeSpan(0, 0, timeout), CacheItemPriority.NotRemovable, null);  
                //绝对过期时间  
                objCache.Insert(cacheKey, objObject, null, DateTime.UtcNow.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            catch (Exception)
            {
                //throw;  
            }
        }
        /// <summary>  
        /// 移除指定数据缓存  
        /// </summary>  
        public static void RemoveAllCache(string cacheKey)
        {
            var cache = HttpRuntime.Cache;
            cache.Remove(cacheKey);
        }
        /// <summary>  
        /// 移除全部缓存  
        /// </summary>  
        public static void RemoveAllCache()
        {
            var cache = HttpRuntime.Cache;
            var cacheEnum = cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                cache.Remove(cacheEnum.Key.ToString());
            }
        }
        public static void SaveCache()
        {
            var cache = HttpRuntime.Cache;
            var cacheEnum = cache.GetEnumerator();
            Dictionary<string, object> dic = new Dictionary<string, object>();
            while (cacheEnum.MoveNext())
            {
                dic.Add(cacheEnum.Key.ToString(), cacheEnum.Value);
            }

            SerializableHelper.Serialize(dic, filePath);
        }
        public static bool LoadCache()
        {
            try
            {
                Dictionary<string, object> dic = (Dictionary<string, object>)SerializableHelper.DeSerialize(filePath);
                if (dic != null && dic.Count > 0)
                {
                    foreach (var item in dic)
                    {
                        SetCache(item.Key, item.Value);
                    }
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 全局变量
        /// </summary>
        public static List<Variable> Var
        {
            get
            {
                var result = (List<Variable>)GetCache(CONST.VARIABLE);
                return result == null ? new List<Variable>() : result;
            }
        }
        public static T GetVar<T>(string key)
        {
            T result = default;
            var cVar = (List<Variable>)GetCache(CONST.VARIABLE);
            var find = cVar.Where(p => p.Name == key).FirstOrDefault();
            if (find == null)
                return result;
            try
            {
                //分类型
                switch (find.DataType)
                {
                    case "System.Int":
                        if (int.TryParse(find.Val.ToString(), out var _int))
                            result = (T)find.Val;
                        break;
                    case "System.Bool":
                        if (bool.TryParse(find.Val.ToString(), out var _bool))
                            result = (T)find.Val;
                        break;
                    case "System.Double":
                        if (bool.TryParse(find.Val.ToString(), out var _double))
                            result = (T)find.Val;
                        break;
                    case "System.Float":
                        if (bool.TryParse(find.Val.ToString(), out var _float))
                            result = (T)find.Val;
                        break;
                    default:
                        result = (T)find.Val;
                        break;
                }
            }
            catch (Exception ex)
            {
                Log4.Error("【全局变量获取】" + ex.Message);
            }

            return result;
        }
        public static bool SetVar<T>(string key, T val)
        {
            var result = (List<Variable>)GetCache(CONST.VARIABLE);
            var find = result.Where(p => p.Name == key).FirstOrDefault();
            if (find == null)
                return false;

            try
            {
                //分类型
                switch (val.GetType().ToString())
                {
                    case "System.Int":
                        if (int.TryParse(val.ToString(), out var _int))
                            find.Val = _int;
                        break;
                    case "System.Bool":
                        if (bool.TryParse(val.ToString(), out var _bool))
                            find.Val = _bool;
                        break;
                    case "System.Double":
                        if (bool.TryParse(val.ToString(), out var _double))
                            find.Val = _double;
                        break;
                    case "System.Float":
                        if (bool.TryParse(val.ToString(), out var _float))
                            find.Val = _float;
                        break;
                    default:
                        find.Val = val.ToString();
                        break;
                }
            }
            catch (Exception ex)
            {
                Log4.Error("【全局变量赋值】" + ex.Message);
                return false;
            }

            return true;
        }
    }

}
